const { Controller } = require('egg');
const { archi } = require('../utils/archi');

class ModelController extends Controller {
  async getModelFunction() {
    const { ctx } = this;
    const { id } = ctx.request.body;
    const { func } = (await this.app.mysql.query(`select func from project where id = ?`, [id]))[0];

    ctx.body.content = func ? JSON.parse(func) : [];
  }

  async getModelModule() {
    const { ctx } = this;
    const { id } = ctx.request.body;
    const { module } = (
      await this.app.mysql.query(`select module from project where id = ?`, [id])
    )[0];

    ctx.body.content = module ? JSON.parse(module) : module;
  }

  async getModelArchitecture() {
    const { ctx } = this;
    const { id, isEdit } = ctx.request.body;
    const architecture =
      archi[id] ||
      JSON.parse(
        (await this.app.mysql.query(`select architecture from project where id=?`, [id]))[0]
          .architecture || '[]'
      );
    if (!archi[id] && isEdit) {
      archi[id] = architecture;
    }
    ctx.body.content = architecture;
  }

  async saveModelArchitecture() {
    const { ctx } = this;
    const { id, architecture } = ctx.request.body;
    await this.app.mysql.query(`update project set architecture=? where id=?`, [
      JSON.stringify(architecture),
      id,
    ]);
  }
}

module.exports = ModelController;
